import pyttsx3
import wave
import numpy as np
from scipy import signal
import os
import time

def main():
    try:
        # 初始化TTS引擎
        engine = pyttsx3.init()
        text = "您的脉搏，高压120，低压80，心跳60，健康状况良好，今天天气晴朗"
        output_file = 'health_report_16k8bitmono.wav'
        temp_file = 'temp_audio.wav'
        
        # 检查目标文件是否存在
        if os.path.exists(output_file):
            # 创建带时间戳的备份文件
            timestamp = time.strftime("%Y%m%d-%H%M%S")
            backup_file = f"backup_{timestamp}_{output_file}"
            os.rename(output_file, backup_file)
            print(f"目标文件已存在，已备份为: {backup_file}")
        
        # 检查临时文件是否存在，存在则删除
        if os.path.exists(temp_file):
            try:
                os.remove(temp_file)
                print(f"已删除旧临时文件: {temp_file}")
            except Exception as e:
                print(f"删除临时文件失败: {str(e)}")
                temp_file = f"temp_{int(time.time())}.wav"
                print(f"使用新临时文件: {temp_file}")
        
        # 生成原始语音
        engine.save_to_file(text, temp_file)
        engine.runAndWait()
        print(f"已生成临时音频: {temp_file}")
        
        # 读取音频并直接处理
        with wave.open(temp_file, 'rb') as wav_in:
            params = wav_in.getparams()
            frames = wav_in.readframes(params.nframes)
            
            # 转换为numpy数组并处理声道
            audio = np.frombuffer(frames, dtype=np.int16)
            if params.nchannels > 1:
                audio = audio[::params.nchannels]  # 取左声道
            
            # 高效重采样到16kHz
            if params.framerate != 16000:
                ratio = 16000 / params.framerate
                audio = signal.resample(audio, int(len(audio) * ratio))
            
            # 优化8bit转换算法 (0-255范围)
            audio = np.clip((audio / 32768) * 128 + 128, 0, 255).astype(np.uint8)
        
        # 写入最终文件
        with wave.open(output_file, 'wb') as wav_out:
            wav_out.setparams((1, 1, 16000, 0, 'NONE', 'not compressed'))
            wav_out.writeframes(audio.tobytes())
        
        print(f"转换完成 (16kHz/8bit/单声道): {output_file}")
        
        # 清理临时文件（带重试机制）
        max_retries = 3
        for attempt in range(max_retries):
            try:
                if os.path.exists(temp_file):
                    os.remove(temp_file)
                    print(f"已清理临时文件: {temp_file}")
                break
            except Exception as e:
                if attempt < max_retries - 1:
                    print(f"删除临时文件失败，重试中... ({attempt+1}/{max_retries})")
                    time.sleep(0.5)
                else:
                    print(f"无法删除临时文件: {temp_file} - 请手动删除")
    
    except Exception as e:
        print(f"处理出错: {str(e)}")
        if os.path.exists(temp_file):
            print(f"已保留临时音频文件: {temp_file}")

if __name__ == "__main__":
    main()